<template>
  <section class="container">

    <section class='body'>
      <div class="button-group">
        <el-button
          type="warning"
          :loading="restartGatewayLoading"
          @click="restartGateway"
          >重启</el-button
        >
        <el-button
          type="warning"
          :loading="resetGatewayLoading"
          @click="resetGateway"
          >恢复出场设置</el-button
        >
        <el-button type="primary" @click="exportGwConf">导出</el-button>
        <el-button type="primary" @click="uploadToGateway" >上传网关配置</el-button>
      </div>
      <ft-table
        ref="gatewayTable"
        :data="gatewayData"
        :columns="gatwayColumns"
        default-expand-all
        @expand-change="gatewayExpand"
        :cell-style="{ background: 'rgba(84, 92, 100, 0.25)' }"
      >
        <template #expand="{ row }">
          <!-- 通道 -->
          <ft-table
            ref="chanelTable"
            :data="chanelData"
            :columns="chanelColumns"
            :expand-row-keys="chanelExpandRows"
            row-key="id"
            @expand-change="chanelExpand"
            :cell-style="{ background: 'rgba(84, 92, 100, 0.33)' }"
          >
            <template #expand="{ row }">
              <!-- 设备 -->
              <ft-table
                ref="deviceTable"
                :data="deviceData"
                :columns="deviceColumns"
                :expand-row-keys="deviceExpandRows"
                row-key="id"
                @expand-change="deviceExpand"
                :cell-style="{ background: 'rgba(84, 92, 100, 0.4)' }"
              >
                <template #expand="{ row }">
                  <!-- tag -->
                  <ft-table
                    ref="tagTable"
                    :data="tagData"
                    :columns="tagColumns"
              
                    :cell-style="{ background: 'rgba(84, 92, 100, 0.5)' }"
                  >
                    <template #operation="{ row }"  v-if="is_admin">
                      <i
                        class="el-icon-edit-outline color-blue left-space"
                        @click="editTag(row)"
                      ></i>
                      <i
                        class="el-icon-delete color-danger left-space"
                        @click="delTag(row)"
                      ></i>
                    </template>
                  </ft-table>
                </template>

                <template #operation="{ row }"  v-if="is_admin">
                  <el-button type="text" @click="addTag(row)"
                    >添加TAG</el-button
                  >
                  <el-button type="text" @click="importTag(row)">
                    <el-upload
                      ref="upload"
                      :action="action"
                      :show-file-list="false"
                      :on-success="tagUploadSuccess"
                      :on-error="tagUploadError"
                      accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel"
                    >
                      导入TAG
                    </el-upload>
                  </el-button>
                  <i
                    class="el-icon-edit-outline color-blue left-space"
                    @click="editDevice(row)"
                  ></i>
                  <i
                    class="el-icon-delete color-danger left-space"
                    @click="delDevice(row)"
                  ></i>
                </template>
              </ft-table>
            </template>

            <template #operation="{ row }"  v-if="is_admin">
              <el-button type="text" @click="addDevice(row)"
                >添加设备</el-button
              >
              <i
                class="el-icon-edit-outline color-blue left-space"
                @click="editChanel(row)"
              ></i>
              <i
                class="el-icon-delete color-danger left-space"
                @click="delChanel(row)"
              ></i>
            </template>
          </ft-table>
        </template>

        <template #operation="{ row }"  v-if="is_admin">
         
          <el-button type="text" @click="addChanel(row)">添加通道</el-button>

          <el-button
            type="text"
            icon="el-icon-edit-outline"
            @click="editGateway(row)"
          ></el-button>
          <i
            class="el-icon-delete color-danger left-space"
            @click="delGateway(row)"
          ></i>
        </template>
      </ft-table>
    </section>

    <el-drawer
      ref="drawer"
      style="display: none"
      :visible.sync="showDrawer"
      :with-header="false"
    >
      <h3>{{ drawerTitle }}</h3>
      <div class="form-body">
        <form-gateway
          v-if="/网关/.test(drawerTitle)"
          :data="gateway"
          @close="showDrawer = false"
          @refresh="refreshGateway"
        ></form-gateway>
        <form-chanel
          v-if="/通道/.test(drawerTitle)"
          :data="chanel"
          @close="showDrawer = false"
          @refresh="refreshChanel"
        ></form-chanel>
        <form-device
          v-if="/设备/.test(drawerTitle)"
          :data="device"
          @close="showDrawer = false"
          @refresh="refreshDevice"
        ></form-device>
        <form-tag
          v-if="/TAG/.test(drawerTitle)"
          :data="tag"
          @close="showDrawer = false"
          @refresh="refreshTag"
        ></form-tag>
      </div>
    </el-drawer>

    <el-dialog
      title="请选择用户后导出网关配置"
      :visible.sync="gatewayDialog"
      width="30%"
    >
      <el-form :model="user" :rules="userRules" ref="user">
        <el-form-item label="用户名称" prop="id">
          <el-select v-model="user.id" placeholder="请选择用户名称">
            <el-option
              v-for="item in users"
              :key="item.id"
              :label="item.user"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="gatewayDialog = false">取 消</el-button>
        <el-button
          type="primary"
          :loading="dialogLoading"
          @click="confirmExport"
          >确 定</el-button
        >
      </span>
    </el-dialog>

  </section>
</template>

<script>
import {
  gatewayApi,
  deviceApi,
  chanelApi,
  tagApi,
  exportGwConfApi,
  delGatewayApi,
  delChanelApi,
  delDeviceApi,
  delTagApi,
  restartGatewayApi,
  resetGatewayApi,
  uploadToGatewayApi,
} from "@/api/setting.js";

import { isDel, isConfirm, download } from "@/util/comman";

import { getUserApi } from "@/api/user";
import config from "@/../config";
import { mapGetters } from "vuex";

import FormGateway from "./form-gateway";
import FormChanel from "./form-chanel";
import FormDevice from "./form-device";
import FormTag from "./form-tag";
import TheUser from "../user";

export default {
  name: "device",
  components: {
    FormGateway,
    FormChanel,
    FormDevice,
    FormTag,
    TheUser,
  },
  data() {
    return {
      gatwayColumns: [
        { prop: "expand", align: "center", type: "expand", slot: true },
        { prop: "name", label: "网关名称", align: "center" },
        { prop: "sn", label: "SN码", align: "center" },
        { prop: "ip", label: "ip", align: "center" },
        { prop: "operation", label: "操作", align: "center", slot: true },
      ],
      gatewayData: [],
      chanelColumns: [
        { prop: "expand", align: "center", type: "expand", slot: true },
        { prop: "type", label: "类型", align: "center" },
        { prop: "protocol", label: "协议", align: "center" },
        { prop: "nb", label: "通道编号", align: "center" },
        { prop: "spd", label: "波特率", align: "center" },
        { prop: "dbs", label: "数据位", align: "center" },
        { prop: "sbs", label: "停止位", align: "center" },
        { prop: "py", label: "校验位", align: "center" },
        { prop: "tot", label: "超时周期(ms)", align: "center" },
        { prop: "operation", label: "操作", align: "center", slot: true },
      ],
      chanelData: [],
      deviceColumns: [
        { prop: "expand", align: "center", type: "expand", slot: true },
        { prop: "name", label: "设备名称", align: "center" },
        { prop: "addr", label: "设备地址", align: "center" },
        { prop: "shortb", label: "2字节", align: "center" },
        { prop: "intb", label: "4字节", align: "center" },
        { prop: "doubleb", label: "8字节", align: "center" },
        { prop: "strb", label: "字符串", align: "center" },
        { prop: "operation", label: "操作", align: "center", slot: true },
      ],
      deviceData: [],
      tagColumns: [
        { prop: "nnm", label: "TAG名称", align: "center" },
        { prop: "cd", label: "功能码", align: "center" },
        { prop: "rsa", label: "寄存器起始地址",align: "center" },
        { prop: "dt", label: "数据类型", align: "center" },
        { prop: "rn", label: "寄存器个数", align: "center" },
        { prop: "rt", label: "倍率", align: "center" },
        { prop: "rw", label: "读写标识", align: "center" },
        { prop: "operation", label: "操作", align: "center", slot: true },
      ],
      tagData: [],
      chanelExpandRows: [],
      deviceExpandRows: [],
      drawerTitle: "网关",
      showDrawer: false,
      loading: false,
      chanel: {},
      device: {},
      tag: {},
      action: "",
      gatewayDialog: false,
      user: {
        id: "",
      },
      users: [],
      userRules: {
        id: [{ required: true, trigger: "blur", message: "请选择用户名称" }],
      },
      dialogLoading: false,
      currentGw: {},
      ip: {},
      restartGatewayLoading: false,
      resetGatewayLoading: false,
    };
  },
  computed: {
    ...mapGetters(["gateway", 'userInfo']),
    is_admin(){
      return this.userInfo.is_admin == 1? true: false;
    }
  },
  mounted() {
    this.getUsers();
    this.$nextTick(()=>{
      this.gatewayData = [this.gateway];
      this.refreshChanel( {parent_id: this.gateway.id});
    })
  },
  methods: {
    getUsers() {
      getUserApi().then((res) => {
        if (res.code == 0) this.users = res.data;
      });
    },
    refreshGateway(data) {
      gatewayApi(data).then((res) => {
        if (res.code == 0) {
          res.data.forEach(item=>{
            if(item.id == this.gateway.id) {
              this.gateway = item;
              this.gatewayData = [item];
            }
          })
        }
      });
    },
    refreshDevice(data) {
      deviceApi(data).then((res) => {
        if (res.code == 0) {
          this.deviceData = res.data;
        }
      });
    },
    refreshChanel(data) {
      chanelApi(data).then((res) => {
        if (res.code == 0) {
          this.chanelData = res.data;
        }
      });
    },
    refreshTag(data) {
      tagApi(data).then((res) => {
        if (res.code == 0) {
          this.tagData = res.data;
        }
      });
    },
    uploadToGateway() {
      uploadToGatewayApi(this.gateway).then(res => {
        if(res.code == 0){
          this.$message({
            type: 'success',
            message: '成功更新配置至网关'
          })
        }
      })
    },
    addChanel(row) {
      this.chanel = {
        parent_id: row.id,
        type: "网口",
        protocol: "modbus",
        nb: "com1",
        spd: "9600",
        dbs: "8",
        sbs: "1",
        py: "N",
        tot: "500",
      };
      this.drawerTitle = "新增通道";
      this.showDrawer = true;
    },
    addDevice(row) {
      this.device = {
        parent_id: row.id,
        dnm: "",
        addr: "",
        shortb: "AB",
        intb: "AB CD",
        doubleb: "AB CD EF GH",
        strb: "Little",
      };
      this.drawerTitle = "新增设备";
      this.showDrawer = true;
      this.$refs.chanelTable.toggleRowExpansion(row);
    },

    addTag(row) {
      this.tag = {
        parent_id: row.id,
        ch: this.chanelExpandRows[0].nb,
        gw_id: this.gateway.id,
        nnm: "",
        cd: "01",
        rsa: "",
        rn: "",
        rt: "9600",
        rw: "0",
      };
      this.drawerTitle = "新增TAG";
      this.showDrawer = true;
      this.$refs.deviceTable.toggleRowExpansion(row);
    },
    gatewayExpand(row) {
      this.refreshChanel({ parent_id: row.id });
    },
    chanelExpandRowKey(row){
      return row.id;
    },
    chanelExpand(row, expandedRows) {
      if (expandedRows.length) {
        this.chanelExpandRows = []
        if (row) {
          this.chanelExpandRows.push(row.id)
        }
      } else {
        this.chanelExpandRows = [];
      }
      this.refreshDevice({ parent_id: row.id });
    },
    deviceExpand(row, expandedRows) {
      if (expandedRows.length) {
        this.deviceExpandRows = []
        if (row) {
          this.deviceExpandRows.push(row.id)
        }
      } else {
        this.deviceExpandRows = [];
      }
      this.refreshTag({ parent_id: row.id });
    },
    editGateway(row) {
      this.drawerTitle = "编辑网关";
      this.showDrawer = true;
      this.gateway = row;
    },
    editChanel(row) {
      this.drawerTitle = "编辑通道";
      this.showDrawer = true;
      this.device = row;
    },
    editDevice(row) {
      this.drawerTitle = "编辑设备";
      this.showDrawer = true;
      this.chanel = row;
    },
    editTag(row) {
      this.drawerTitle = "编辑TAG";
      this.showDrawer = true;
      this.tag = row;
    },
    async delGateway(row) {
      const flag = await isDel(row.name);
      if (!flag) return;
      delGatewayApi({ id: row.id }).then((res) => {
        if (res.code == 0) {
          this.$message({ type: "success", message: "网关删除成功" });
          this.refreshGateway();
        } else {
          this.$message({ type: "warning", message: "网关删除失败" });
        }
      });
    },
    async delChanel(row) {
      const flag = await isDel(row.com);
      if (!flag) return;
      delChanelApi({ id: row.id }).then((res) => {
        if (res.code == 0) {
          this.$message({ type: "success", message: "通道删除成功" });
          this.refreshChanel({ parent_id: row.parent_id });
        } else {
          this.$message({ type: "warning", message: "通道删除失败" });
        }
      });
    },
    async delDevice(row) {
      const flag = await isDel(row.name);
      if (!flag) return;
      delDeviceApi({ id: row.id }).then((res) => {
        if (res.code == 0) {
          this.$message({ type: "success", message: "设备删除成功" });
          this.refreshDevice({ parent_id: row.parent_id });
        } else {
          this.$message({ type: "warning", message: "设备删除失败" });
        }
      });
    },
    async delTag(row) {
      const flag = await isDel(row.name);
      if (!flag) return;
      delTagApi({ id: row.id }).then((res) => {
        if (res.code == 0) {
          this.$message({ type: "success", message: "tag删除成功" });
          this.refreshTag({ parent_id: row.parent_id });
        } else {
          this.$message({ type: "warning", message: "tag删除失败" });
        }
      });
    },
    exportGwConf() {
      this.gatewayDialog = true;
      this.currentGw = this.gateway;
      this.user.id = "";
    },
    confirmExport() {
      this.$refs.user.validate((valid) => {
        if (valid) {
          this.dialogLoading = true;
          const data = {
            ...this.currentGw,
            userName: this.user.name,
          };
          exportGwConfApi(data).then((res) => {
            this.dialogLoading = false;
            this.gatewayDialog = false;
            if (res.code == 0) {
              console.log(res.data)
              download(res.data, '网关配置.json')
            }
          });
        }
      });
    },
    importTag(row) {
      this.action =
        config.baseURL +
        ":" +
        config.http_server_port +
        "/tag/addByFile?parent_id=" +
        row.parent_id;
    },
    tagUploadSuccess(res) {
      if (res.code == 0)
        this.$message({ type: "success", message: "文件上传成功" });
      else this.$message({ type: "warning", message: "文件上传失败" });
    },
    tagUploadError() {
      this.$message({ type: "warning", message: "文件上传失败" });
    },
    async restartGateway() {
      const flag = await isConfirm(`即将重启网关：${this.gateway.name},是否继续?`);
      if (!flag) return;
      this.restartGatewayLoading = true;
      restartGatewayApi().then((res) => {
        this.restartGatewayLoading = false;

        if (res.code == 0) {
          this.$message({ type: "success", message: "重启成功" });
        }
      });
    },
    async resetGateway() {
      const flag = await isConfirm(`网关${this.gateway.name}即将恢复出厂设置,是否继续?`);
      if (!flag) return;
      this.resetGatewayLoading = true;

      resetGatewayApi().then((res) => {
        this.resetGatewayLoading = false;
        if (res.code == 0) {
          this.$message({ type: "success", message: "恢复出厂设置成功" });
        }
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.container {
  display: flex;
  overflow: hidden;
  .body {
    width: 100%;
  }
  .ft-table {
    width: 100%;
  }
}
.button-group {
  display: flex;
  justify-content: flex-end;
  padding: 10px;
}
.form-body {
  max-height: 75vh;
  overflow: auto;
}
</style>